//
//  RHMeDeviceInfoVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/7.
//

#import "RHMeDeviceInfoVC.h"
#import "DevChartParamsModel.h"
#import "DevChartModel.h"
#import "SYChartTool.h"
#import "RHDeviceModel.h"
#import "RHMeDeviceInfoCell.h"
#import "RHMePlantInfoChartCell.h"
#import "RHMeDeviceEndpointCell.h"
#import "WSDatePickerView.h"
#import "RHMeEndpointTypeModel.h"
#import "RHDeviceInfoController.h"
#import "RHDeviceDetailModel.h"
#import "RHMeDeviceFullChartVC.h"
#import "RHDeviceBatteryVC.h"

@interface RHMeDeviceInfoVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *endpointTypeArr;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

@property (nonatomic ,strong) RHDeviceDetailModel *infoModel;
@end

@implementation RHMeDeviceInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = self.devModel.deviceId;
  
    [self createData];
    [self setupUI];
    [self getData];
}

-(void)getData
{
    [self getDeviceInfo];
    [self getChartData];
}

-(void)getChartData
{
    for (int i = 0; i<self.chartParamsModel.chartList.count; i++) {
        DevChartModel *chartModel = self.chartParamsModel.chartList[i];
        if (i == 1) {
            [self getDeviceAlarmDataWithChartModel:chartModel];
        }else{
            [self getEnergyStatisticsWithChartModel:chartModel];
        }
    }
    
}

-(void)createData
{
    NSArray *lineColors = @[@[@"#46ECA6",@"#678EF2"],@[@"#FFCE00",@"#F9588A"],@[@"#B656F8",@"#46ECA6",@"#678EF2"]];
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"ME_PlantDeviceInfoStatistics"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
    NSArray *chartTitles = @[@"充放电量趋势".rh_localized,@"故障告警趋势".rh_localized,@"设备温度曲线".rh_localized];
    [chartTitles enumerateObjectsUsingBlock:^(NSString*  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
       DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:idx];
        chartModel.title = title;
        chartModel.colorArr = [lineColors safeObjectAtIndex:idx];
    }];
}

-(void)getDeviceInfo
{
 
    NSDictionary *para = @{
        @"deviceId":self.devModel.deviceId
    };
    [RHDeviceDetailModel startGetWithCompletionAPIKey:H_MeDeviceMonitorDetail argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if (resultModel.code == 200) {
            self.infoModel = resultModel.data;
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


- (void)setupUI{
    kWeakSelf;
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHMeDeviceInfoCell class] forCellReuseIdentifier:@"RHMeDeviceInfoCell"];
    [_tableView registerClass:[RHMeDeviceEndpointCell class] forCellReuseIdentifier:@"RHMeDeviceEndpointCell"];
    [_tableView registerClass:[RHMePlantInfoChartCell class] forCellReuseIdentifier:@"RHMePlantInfoChartCell_lineChart"];
    [_tableView registerClass:[RHMePlantInfoChartCell class] forCellReuseIdentifier:@"RHMePlantInfoChartCell_barChart"];
  
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getDeviceInfo];
        [weakSelf getChartData];
    }];
}


-(void)getDataWithChartModel:(DevChartModel*)chartModel index:(NSInteger)index
{
    if (index == 1) {//故障告警次数
        [self getDeviceAlarmDataWithChartModel:chartModel];
    }else{
        [self getEnergyStatisticsWithChartModel:chartModel];
    }
}

// 充放电 设备温度温度 H_getRegularStatistics
-(void)getEnergyStatisticsWithChartModel:(DevChartModel*)chartModel
{
    
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    [BaseModel startWithCompletionAPIKey:H_getRegularStatistics argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        chartModel.allDataArray = request.responseJSONObject[@"data"];
//        chartModel.allDataArray = [chartModel getTestData];
        
        [self.tableView reloadData];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

// 故障告警
-(void)getDeviceAlarmDataWithChartModel:(DevChartModel*)chartModel
{
    
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    [BaseModel startWithCompletionAPIKey:H_getDeviceAlarmLineData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        chartModel.allDataArray = request.responseJSONObject[@"data"];
//        chartModel.allDataArray = [chartModel getTestData];
        
        [self.tableView reloadData];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return self.chartParamsModel.chartList.count;
    }
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

   return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        return 15;
    }
    if (section == 3) {
        return 10;
    }
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        RHMeDeviceInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMeDeviceInfoCell"];
      
        [cell setInfoModel:self.infoModel];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if(indexPath.section == 1){
        kWeakSelf;
        //部件图
        RHMeDeviceEndpointCell *endpointCell = [tableView dequeueReusableCellWithIdentifier:@"RHMeDeviceEndpointCell"];
        
        endpointCell.infoModel = self.infoModel;
        
        endpointCell.clickDeviceBlock = ^(RHMeEndpointTypeModel * _Nonnull endpointModel) {
            [weakSelf clickEndpoint:endpointModel];
        };
        endpointCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return endpointCell;
    }else if(indexPath.section == 2){
        kWeakSelf;
        //能量统计
        RHMePlantInfoChartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoChartCell_lineChart"];
        if (indexPath.row == 0) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoChartCell_barChart"];
        }
        DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexPath.row];
        [cell setChartModel:chartModel];
        //选择参数
        cell.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index atIndexpath:indexPath];
        };
        
        cell.subTimeBlock = ^{//日期往前
            [weakSelf subTimeAction:indexPath];
        };
        
        cell.addTimeBlock = ^{//日期往后
            [weakSelf addTimeAction:indexPath];
        };
        
        cell.changeTimeBlock = ^{//选择日期
            [weakSelf changeDate:indexPath];
        };
        
        //全屏
        cell.fullChartBlock = ^{
            [weakSelf fullAction:indexPath.row];
        };
        cell.contentView.backgroundColor = CFTabViewBgColor;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
    return [UITableViewCell new];
}



//M1001RE1001011     DEV1691735407840   DEV1691735407840  DEV1691735407840
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}


#pragma mark ----------------- Action --------------------
#pragma mark ----- 点击端点
-(void)clickEndpoint:(RHMeEndpointTypeModel*)endPointTypeModel
{
   
        RHDeviceInfoController *deviceInfoVC = [[RHDeviceInfoController alloc]initWithDevModel:self.devModel endpointName:endPointTypeModel.endpointTypeCode];
       
        [self.navigationController pushViewController:deviceInfoVC animated:YES];
    
}
#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------
//工具选择项
- (void)selectTopTool:(NSInteger)index atIndexpath:(NSIndexPath *)indexpath{
    
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
    
    
    if (index == 0) {//Day
        chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.dayParams;
        [self.tableView reloadData];
       
    }else if (index == 1) {//Month
        chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.monthParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 2) {//Year
        chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.yearParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 4) {//Total
        chartModel.timeType = TimeType_Total;
       
    }
    
    [self getDataWithChartModel:chartModel index:indexpath.row];

}
#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
   
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYear;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        
       
        [self getDataWithChartModel:chartModel index:indexpath.row];
       
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
#pragma mark ------ 后一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
  
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%ld",(long)interval];
    
    
   
    [self getDataWithChartModel:chartModel index:indexpath.row];
    
}

#pragma mark ------ 前一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
   
    
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    
    [self getDataWithChartModel:chartModel index:indexpath.row];
   
}


#pragma mark ---- 全屏
- (void)fullAction:(NSInteger)index{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:index];
    
    NSInteger type = 2;
    if (chartModel.monthParams.count>0) {
        type = 1;
    }
    if (chartModel.yearParams.count>0) {
        type = 0;
    }
    DevChartModel *fullModel = [chartModel modelCopy];
    fullModel.isAllowScale = YES;
    
    BOOL isBarChart = index == 0;
    NSString *url = H_getRegularStatistics;//充放电 设备温度温度
    if (index == 1) {
        url = H_getDeviceAlarmLineData;
    }
    RHMeDeviceFullChartVC *vc = [[RHMeDeviceFullChartVC alloc] initWithModel:fullModel deviceModel:self.devModel toolType:type isBarChart:isBarChart requestUrl:url];
    [self.navigationController pushViewController:vc animated:NO];
   
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
